package com.l2qq.admin.account;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Inject;
import com.jfinal.kit.Kv;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import com.l2qq.admin.login.LoginService;
import com.l2qq.common.kit.CondKit;

import com.l2qq.common.model.Account;

import java.util.Date;

/**
 * 账户管理业务层
 */
public class AccountService {

    private static final int pageSize = 25;
    @Inject
    Account accountDao;
    @Inject
    LoginService loginService;
    @Inject
    AccountTool accountTool;


    /**
     * 创建
     */
    public Ret saveOrUpdate(JSONObject jsonObject) {
        Account account = jsonObject.toJavaObject(Account.class);
        // 统一验证流程
        boolean isNew = account.getId() == null;
        Ret validationResult = accountTool.validate(account, isNew);
        if (validationResult.isFail()) return validationResult;

        // userName 存小写到数据库（不区分大小写）
        if (StrKit.notBlank(account.getUsername())) {
            account.setUsername(account.getUsername().trim().toLowerCase());
        }

        if (isNew) {
            //创建
            Ret retPw = accountTool.passwordSaltAndHash(account);
            if (retPw.isOk()) {
                account.setCreateDate(new Date());
                account.remove("id").save();
            } else {
                return retPw;
            }
        } else {
            account.setUpdateDate(new Date());
            account.removeSensitiveInfo();//删除密码
            account.update();
        }
        return Ret.ok("操作成功").set("id", account.getId());
    }


    public Ret searchByPage(JSONObject jsonObject) {
        Kv cond = CondKit.getCond(jsonObject);
        Page<Account> accounts = accountDao.template("account.searchByPage", cond).paginate(cond.getInt("pageNumber"), cond.getInt("pageSize"));
        return Ret.ok().set("data", accounts);
    }


    public Ret searchByHeard(JSONObject jsonObject) {
        String heardAutoCompleteName = jsonObject.getString("heardAutoCompleteName");
        Page<Record> recordPage = null;
        Kv cond = CondKit.getCond(jsonObject);
        SqlPara sqlPara = Db.template("account.searchByPage", cond).getSqlPara();
        if (!StrKit.isBlank(heardAutoCompleteName)) {
            String sql = "SELECT " + heardAutoCompleteName + " as value  FROM ( " + sqlPara.getSql() + " ) AS a WHERE 1 = 1 ";
            sql = sql + "  group by " + heardAutoCompleteName;
            sql = "select * from ( " + sql + " ) as a where value is not null";
            sqlPara.setSql(sql);
            recordPage = Db.paginate(1, 10, sqlPara);
        }
        return Ret.ok().set("data", recordPage);
    }


    /**
     * 获取
     */
    public Ret detail(int id) {
        Ret ret = Ret.ok();
        Account account = accountDao.findById(id);
        account.removeSensitiveInfo();//删除密码
        return ret.set("data", account);
    }

    /**
     * 删除
     */
    public Ret deleteById(int loginAccountId, int id) {
        if (loginAccountId == id) {
            return Ret.fail("不能删除自己的账户");
        }
        if (id == 1) {
            return Ret.fail("id 值为 1 的账户不能删除");
        }
        boolean b = accountDao.deleteById(id);
        if (b) {
            return Ret.ok("删除成功");

        } else {
            return Ret.fail("账号不存");
        }
    }

    public Ret changePassword(JSONObject jsonObject) {
        Ret ret = Ret.ok();
        String id = jsonObject.getString("id");
        Account account = accountDao.findById(id);
        if (account != null) {
            Ret retPw = accountTool.passwordSaltAndHash(account);
            if (retPw.isOk()) {
                account.update();
            } else {
                return retPw;
            }
        } else {
            return Ret.fail("账号不存在");
        }
        return ret;
    }

}





